<script setup>
import {onMounted, reactive, ref} from 'vue'
import {FormRules} from 'element-plus'
import {ElMessage} from 'element-plus'
import http from '../http/index'
import {useRouter} from "vue-router";
//  验证码
import SIdentify from '@/components/Sidentify.vue';
import store from "@/store";


const ruleFormRef = ref()
// 获取路由器
const router = useRouter()

let  users = JSON.parse(localStorage.getItem("user"))
let  uname = users==null?'':JSON.parse(localStorage.getItem("user")).username
let  pwd = users==null?'':JSON.parse(localStorage.getItem("user")).password

const ruleForm = reactive({
  username: uname,
  password:pwd,
})
//  记住密码
let checked = ref()


//  用户名为空校验
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入账号'))
  } else {
    callback()
  }
}
//  密码为空校验
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{validator: validatePass, trigger: 'blur'}],
  password: [{validator: validatePass2, trigger: 'blur'}]
})


let sidentifyMode = ref('') //输入框验证码
let identifyCode = ref('') //图形验证码
let identifyCodes = ref('1234567890abcdewxbjh') //验证码出现的数字和字母

//组件挂载
onMounted(() => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
})

// 生成随机数
// @ts-ignore
const randomNum = (min, max) => {
  max = max + 1
  return Math.floor(Math.random() * (max - min) + min)
}
// 随机生成验证码字符串
// @ts-ignore
const makeCode = (o, l) => {
  for (let i = 0; i < l; i++) {
    identifyCode.value += o[randomNum(0, o.length)]
  }
}
// 更新验证码
const refreshCode = () => {
  identifyCode.value = ''
  makeCode(identifyCodes.value, 4)
}

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      // valid为true 输入框有值
      console.log(sidentifyMode.value)
      console.log(identifyCode.value)
    } else {
      // 信息未输入警告
      return false
    }
    if (!sidentifyMode.value) {
      ElMessage({type: 'error', message: '请输入验证码'})
      return
    }
    //验证验证码是否正确
    if (sidentifyMode.value != identifyCode.value) {
      ElMessage({type: 'error', message: '验证码错误'})
      refreshCode()
      return
    } else {
      onLogin()
    }

  })

}


//  登录
let onLogin = () => {
  http.post('/login',ruleForm).then(request => {
    console.log(request)
    //登录成功跳转主页面
    // @ts-ignore
    if (request.code == 200) {
      sessionStorage.setItem("user",JSON.stringify(request.data))
      store.commit('getUser',request.data)
      if (checked.value == true){
        localStorage.setItem("user",JSON.stringify(ruleForm))
      }
      // @ts-ignore
      ElMessage({message: request.msg, type: 'success'})
      router.push('/linkhotai/gzt')
    } else {
      // @ts-ignore
      ElMessage.error(request.msg)
    }
  })
}

//  跳转注册页面
const goToPage = () => {
  router.push('/register')
}

</script>

<template>
  <div class="login">
    <div class="login-wrap">
      <img class="login-bg1" src="@/assets/login/login_bg1.png"/>
      <img class="login-bg2" src="@/assets/login/login_bg2.png"/>
      <img class="login-bg3" src="@/assets/login/login_bg3.png"/>
      <div class="login-form-wrap">
        <!-- 登录from表单
         :rules="rules" 校验规则     status-icon 反馈图标  -->
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="auto" class="login-form">
          <h3 class="title">LinkWeChat</h3>
          <el-form-item prop="username">
            <el-input v-model="ruleForm.username" type="text" autocomplete="off" placeholder="账号">
              <template #prefix>
                <el-icon>
                  <UserFilled/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="ruleForm.password" type="password" placeholder="密码">
              <template #prefix>
                <el-icon>
                  <Unlock/>
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="code">
            <el-input v-model="sidentifyMode" clearable type="text" placeholder="验证码" style="width: 200px">
              <template #prefix>
                <el-icon>
                  <Message/>
                </el-icon>
              </template>
            </el-input>
            <!--验证码组件-->
            <div class="login-code" @click="refreshCode">
              <SIdentify :identifyCode="identifyCode"></SIdentify>
            </div>
          </el-form-item>
          <div style=" margin-top: -15px">
            <el-checkbox v-model="checked" value="true"  label="记住密码" size="large"/>
          </div>
          <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
          <el-button class="register" @click="goToPage">手机号注册</el-button>
        </el-form>
      </div>
    </div>

    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2024 LinkWeChat All Rights Reserved.</span>
    </div>

  </div>
</template>


<style rel="stylesheet/scss" lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-size: cover;
}

.login-wrap {
  position: relative;
  width: 1180px;
  height: 733px;
}

[class*='login-bg'] {
  position: absolute;
  z-index: -1;
}

.login-form-wrap {
  position: relative;
  background: #fff;
  height: 609px;
  top: 62px;
  left: 112px;
}

.login-bg1 {
  top: 0;
  left: 0;
  height: 100%;
}

.login-bg2 {
  top: 62px;
  left: 382px;
  z-index: 10;
}

.login-bg3 {
  top: 220px;
  right: 25px;
  z-index: 20;
}

// 底部
.el-login-footer {
  height: 40px;
  line-height: 10px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  z-index: 90;
}


// from表单
.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  position: relative;
  top: 120px;

  .el-input {
    margin-top: 10px;
    height: 35px;
    width: 350px;
  }
}

.title {
  margin: 0px 50px 20px auto;
  text-align: center;
  color: #027dfe;
}

.el-button {
  margin-top: 22px;
  width: 350px;
}

// 注册按钮
.register {
  width: 300px;
  border: 2px solid dodgerblue;
  margin-left: 22px;
  text-align: center;
  color: #027dfe;
}


// 验证码
.login-code {
  width: 114px;
  height: 40px;
  margin: 10px auto auto 20px;
}


</style>